//
//  VerifyCode.swift
//  App
//
//  Created by 汤泽川 on 2019/3/25.
//

import Foundation
import Vapor
import Random

struct VerifyCode : BaseModel {
    var createdAt: Date?
    var updatedAt: Date?
    
    var id : Int?
    var email : String?
    var code : String?
    var expire : Date?
    
    init(email : String, code : String) {
        self.email = email
        self.code = code
    }
    
    init(email : String) {
        self.email = email
    }
    
    init() {
        
    }
}

extension VerifyCode {
    mutating func createVerifyCode() {
        self.code = String.randomStr(length: 4)
        updateExpire()
    }
    
    mutating func updateExpire() {
        self.expire = Date().addingTimeInterval(30 * 60)
    }
    
    func isExpire() -> Bool {
        guard let expire = expire else {
            return true
        }
        let remainTime = expire.timeIntervalSinceNow
        if remainTime > 0.0 {
            return false
        } else {
            return true
        }
    }
}

extension VerifyCode {
    func sendVerifyByEmail(req : Request) throws -> Future<Bool> {
        guard let email = self.email else {
            throw APIError.emptyEmailError
        }
        var emailContent = EmailContent(email: email)
        emailContent.subject = "欢迎使用Story"
        emailContent.text = "您的验证码为\(self.code ?? "0")"
        return try EmailSender.sendEmail(req, content: emailContent)
    }
}


/// 随机字符串生成
extension String {
    fileprivate static let RandomRangeStr = "1234567890"
    
    /**
     生成随机字符串,
     
     - parameter length: 生成的字符串的长度
     
     - returns: 随机生成的字符串
     */
    static func randomStr(length: Int) -> String {
        var ranStr = ""
        for _ in 0..<length {
            let index : Int
            do {
                var random = try OSRandom().generate(Int.self)
                random = abs(random)
                index = random % RandomRangeStr.count
            } catch {
                index = 0
            }
            ranStr.append(RandomRangeStr[RandomRangeStr.index(RandomRangeStr.startIndex, offsetBy: index)])
        }
        return ranStr
    }
}
